package com.dcits.account.common;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: 2843896844@qq.com
 * @Date: 2021/01/13/10:03
 * @Description: 线程池组件，内部封装一个通用线程池，单例
 */
public class ThreadPoolCompoent {

    private ExecutorService executor;

    private ThreadPoolCompoent() {
        int cpuCount = Runtime.getRuntime().availableProcessors();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
        executor = new ThreadPoolExecutor(
                cpuCount,
                cpuCount*2,
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10),
                new ThreadFactory() {
                    final AtomicInteger threadNumber = new AtomicInteger(1);

                    @Override
                    public Thread newThread(Runnable runnable) {
                        Thread thread = new Thread(
                                Thread.currentThread().getThreadGroup(),
                                runnable,
                                "thread-pool-" + threadNumber.getAndIncrement(),
                                0);
                        thread.setDaemon(true);
                        if (thread.getPriority() != Thread.NORM_PRIORITY) {
                            thread.setPriority(Thread.NORM_PRIORITY);
                        }
                        return thread;
                    }
                }, handler);
    }

    public Future<?> submit(Runnable runnable) {
        return executor.submit(runnable);
    }

    public Future<?> submit(Callable<?> callable) {
        return executor.submit(callable);
    }

    private static ThreadPoolCompoent instance = new ThreadPoolCompoent();


    public static ThreadPoolCompoent getInstance() {
        return instance;
    }
}
